const { sms } = require('../../server_config.json');
const SMSClient = require('@alicloud/sms-sdk')
const logger = require('./log').logger;
const { messageAdd, messageUpdate } = require('../services/message');
const { Exec, ExecGetOne } = require('../db/dbhelper');

async function sendmsg_sms(phone, name) {
    try {
        const accessKeyId = sms.AccessKeyID;
        const secretAccessKey = sms.AccessKeySecret;
        const originname = sms.originname;
        const TemplateCode = sms.TemplateCode;
        //初始化sms_client
        let smsClient = new SMSClient({ accessKeyId, secretAccessKey })
        //发送短信
        let message = {
            PhoneNumbers: phone,
            SignName: originname,
            TemplateCode: TemplateCode,
            TemplateParam: `{"name":"${name}"}`
        };
        let messageObj = {
            pcode: pcode,
            phone: phone,
            msg: JSON.stringify(message),
            type: '邀请体验',
            mode: '短信'
        };
        let result = await smsClient.sendSMS(message);
        if (result) {
            messageObj.bizid = result.BizId;
            messageObj.errmsg = result.Message;
            if (result.code == 'OK') {
                messageObj.issend = 1;
            }
        }
        await messageAdd(messageObj);
        return {
            code: 0,
            msg: '发送成功'
        };
    } catch (error) {
        logger.info(`----------sendmsg_sms---------error,`, error);
        return {
            code: 1,
            msg: '发送失败' + (error ? error.stock : '')
        }
    }
}

async function init_auth() {
    let list1 = await Exec(`select * from hzz_autheducations`);
    for (const item of list1) {
        let file = await ExecGetOne(`select * from hzz_ossfiles where pcode=${item.pcode} and type='学历认证' order by createtime desc`);
        if (file) {
            await Exec(`update hzz_autheducations set img='${file.url}' where id = ${item.id}`)
        }
    }
    let list2 = await Exec(`select * from hzz_authworks`);
    for (const item of list2) {
        let file = await ExecGetOne(`select * from hzz_ossfiles where pcode=${item.pcode} and type='工作认证' order by createtime desc`);
        if (file) {
            await Exec(`update hzz_authworks set img='${file.url}' where id = ${item.id}`)
        }
    }
    return {
        code: 0,
        msg: 'ok'
    }
}

module.exports = {
    sendmsg_sms,
    init_auth
}